/*
 * @Autor: CQJ
 * @Date: 2022-08-15 13:41:15
 * @LastEditors: CQJ
 * @LastEditTime: 2022-08-22 01:05:31
 * @Description:
 */
import { PermissionState } from '@/types/store/permission';
import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes } from '@/router';
// import { listRoutes } from '@/api/system/menu';
//模拟路由
import { routesData } from './test'
const modules = import.meta.glob('../../views/**/**.vue');
export const Layout = () => import('@/layout/index.vue');

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    if (roles.includes('ROOT')) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return false;
};

export const filterAsyncRoutes = (
  routes: any[],
  roles: string[],
) => {
  const res: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmp = { ...route } as any;
    if (hasPermission(roles, tmp)) {
      if (tmp.component == 'Layout') {
        tmp.component = Layout;
      } else {
        const component = modules[`../../views/${tmp.component}.vue`] as any;
        if (component) {
          tmp.component = modules[`../../views/${tmp.component}.vue`];
        } else {
          tmp.component = modules[`../../views/error-page/404.vue`];
        }
      }
      res.push(tmp);

      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
    }
  });
  return res;
};

const usePermissionStore = defineStore({
  id: 'permission',
  state: (): PermissionState => ({
    routes: [],
    pointRouters: [],
    originRouter: [],
    siteName: '返回'
  }),
  // 所有数据持久化
  // persist: true,
  // 持久化存储插件其他配置
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'siteName',
    // 修改为 sessionStorage，默认为 localStorage
    storage: window.sessionStorage,
    // 部分持久化状态的点符号路径数组，[]意味着没有状态被持久化(默认为undefined，持久化整个状态)
    paths: ['siteName'],
  },
  actions: {
    // initMenus(route) {
    //   const path = route.path;
    //   if (path.includes('popularize-manage')) {
    //     this.pointRouters = this.routes.filter(item => item.name === 'PopularizeManage')[0].children || [];
    //   } else if (path.includes('game-box')) {
    //     this.pointRouters = this.routes.filter(item => item.name === 'GameBox')[0].children || [];
    //   } else {
    //     this.pointRouters = this.routes.filter(item => item.name !== 'PopularizeManage' && item.name !== 'GameBox') || [];
    //   }
    // },
    setSiteName(name: string) {
      this.siteName = name
    },
    setRoutes(routes: RouteRecordRaw[]) {
      this.routes = constantRoutes.concat(routes);
    },
    generateRoutes(roles: string[]) {
      return new Promise((resolve) => {
        const _asyncRoutes = routesData;
        this.originRouter = routesData;
        const accessedRoutes = filterAsyncRoutes(_asyncRoutes, roles);
        // this.initMenus()
        this.setRoutes(accessedRoutes);
        this.pointRouters = _asyncRoutes.filter(item => {
          if (item.path == '/system') {
            return item
          }
        })
        resolve(accessedRoutes)

        // listRoutes()
        //   .then((response) => {
        //     const asyncRoutes = response.data;
        //     const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        //     this.setRoutes(accessedRoutes);
        //     resolve(accessedRoutes);
        //   })
        //   .catch((error) => {
        //     reject(error);
        //   });
      });
    },
  },
});

export default usePermissionStore;
